package com.origin.niuke.tree;

import general_class.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * NC224 从下到上打印二叉树
 * 算法：层序遍历 + 栈
 *
 * @author yezh
 * @date 2022/11/28 22:05
 */
public class NC224 {

    public int[][] levelOrderBottom(TreeNode root) {
        // write code here
        Deque<int[]> stack = new ArrayDeque<>();
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size(), row = 0;
            int[] nums = new int[size];
            while (size-- > 0) {
                root = queue.poll();
                nums[row++] = root.val;
                if (root.left != null) queue.offer(root.left);
                if (root.right != null) queue.offer(root.right);
            }
            stack.push(nums);
        }
        int[][] ans = new int[stack.size()][];
        int idx = 0;
        while (!stack.isEmpty()) {
            ans[idx++] = stack.pop();
        }
        return ans;
    }

}
